package com.aiwiown.snackmq.network.handler;

import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.EnumMap;
import java.util.Map;

/**
 * 客户端侧的消息分发器。
 * 这是一个 Inbound-Handler，用于接收和分发来自 Broker 的请求。
 */
@Slf4j
@ChannelHandler.Sharable
public class ClientMessageDispatcher extends SimpleChannelInboundHandler<Message> {

    private final Map<MessageType, ClientMessageHandler> handlerMap = new EnumMap<>(MessageType.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        ClientMessageHandler handler = handlerMap.get(msg.getType());
        if (handler != null) {
            log.debug("Client received a request from broker: {}", msg.getType());
            handler.handle(msg);
        } else {
            // 如果没有找到处理器，可能是一个对请求的响应，交由下一个 handler 处理
            ctx.fireChannelRead(msg);
        }
    }

    public void registerHandler(ClientMessageHandler handler) {
        if (handler != null && handler.getMessageType() != null) {
            handlerMap.put(handler.getMessageType(), handler);
            log.info("Registered client-side handler for message type: {}", handler.getMessageType());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Exception caught in ClientMessageDispatcher.", cause);
        ctx.close();
    }
}